import java.util.concurrent.PriorityBlockingQueue;

//定时器
//表示一个任务
class MyTask implements  Comparable<MyTask>{
    //执行什么人物
    public  Runnable runnable;
    //使用时间戳
    public  long time;

    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //当亲时刻的时间戳+delay 就是实际执行的时间戳
        this.time = System.currentTimeMillis()+delay;
    }

    @Override
    //比较每次取出来的都是最小的时间
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    //优先级队列，存放的是Mytask
    public PriorityBlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();

    //创建一个锁对象
    Object locker=new Object();
    //构造方法
    public void schedule(Runnable runnable,long dealy)
    {
        //根据参数, 构造 MyTask, 插入队列即可
        MyTask myTask=new MyTask(runnable,dealy);
        //放到队列中
        queue.put(myTask);
        //唤醒
        synchronized (locker)
        {
            locker.notify();
        }
    }

    // 在这里构造线程, 负责执行具体任务了.
    public MyTimer(){
        Thread t=new Thread( ()-> {
            while(true)
            {
                try {
                    synchronized (locker) {
                        //取出
                        MyTask myTask = queue.take();
                        //当前时间的时间戳
                        long curtime = System.currentTimeMillis();
                        if (myTask.time <= curtime) {
                            //时间到了，开始执行
                            myTask.runnable.run();
                        } else {
                            //时间还没到，将Mytask再塞回队列中
                            queue.put(myTask);
                            //等待一段时间
                            locker.wait(myTask.time - curtime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        });
        t.start();
    }


}
public class ThreadDemo21 {

    public static void main(String[] args) {
        MyTimer myTimer= new MyTimer();

        //
        myTimer.schedule(new Runnable() {

            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000 );
        myTimer.schedule(new Runnable() {

            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000 );
        myTimer.schedule(new Runnable() {

            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000 );
        myTimer.schedule(new Runnable() {

            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000 );

                System.out.println("hello0");

    }
}
